[[...path]].page.tsx 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684
  1. import React, { ReactNode, useEffect } from 'react';
  2. import EventEmitter from 'events';
  3. import {
  4. isClient, isIPageInfoForEntity, pagePathUtils, pathUtils,
  5. } from '@growi/core';
  6. import type {
  7. IDataWithMeta, IPageInfoForEntity, IPagePopulatedToShowRevision, IUserHasId,
  8. } from '@growi/core';
  9. import ExtensibleCustomError from 'extensible-custom-error';
  10. import type {
  11. GetServerSideProps, GetServerSidePropsContext,
  12. } from 'next';
  13. import { serverSideTranslations } from 'next-i18next/serverSideTranslations';
  14. import dynamic from 'next/dynamic';
  15. import Head from 'next/head';
  16. import { useRouter } from 'next/router';
  17. import superjson from 'superjson';
  18. import { useCurrentGrowiLayoutFluidClassName, useEditorModeClassName } from '~/client/services/layout';
  19. import { PageView } from '~/components/Page/PageView';
  20. import { DrawioViewerScript } from '~/components/Script/DrawioViewerScript'; import type { CrowiRequest } from '~/interfaces/crowi-request';
  21. import type { EditorConfig } from '~/interfaces/editor-settings';
  22. import type { IPageGrantData } from '~/interfaces/page';
  23. import type { RendererConfig } from '~/interfaces/services/renderer';
  24. import type { PageModel, PageDocument } from '~/server/models/page';
  25. import type { PageRedirectModel } from '~/server/models/page-redirect';
  26. import {
  27. useCurrentUser,
  28. useIsForbidden, useIsSharedUser,
  29. useIsEnabledStaleNotification, useIsIdenticalPath,
  30. useIsSearchServiceConfigured, useIsSearchServiceReachable, useDisableLinkSharing,
  31. useHackmdUri, useDefaultIndentSize, useIsIndentSizeForced,
  32. useIsAclEnabled, useIsSearchPage, useIsEnabledAttachTitleHeader,
  33. useCsrfToken, useIsSearchScopeChildrenAsDefault, useCurrentPathname,
  34. useIsSlackConfigured, useRendererConfig, useGrowiCloudUri,
  35. useEditorConfig, useIsAllReplyShown, useIsUploadableFile, useIsUploadableImage, useIsContainerFluid, useIsNotCreatable,
  36. } from '~/stores/context';
  37. import { useEditingMarkdown } from '~/stores/editor';
  38. import { useHasDraftOnHackmd, usePageIdOnHackmd, useRevisionIdHackmdSynced } from '~/stores/hackmd';
  39. import {
  40. useSWRxCurrentPage, useSWRMUTxCurrentPage, useSWRxIsGrantNormalized, useCurrentPageId,
  41. useIsNotFound, useIsLatestRevision, useTemplateTagData, useTemplateBodyData,
  42. } from '~/stores/page';
  43. import { useRedirectFrom } from '~/stores/page-redirect';
  44. import { useRemoteRevisionId } from '~/stores/remote-latest-page';
  45. import { useSelectedGrant } from '~/stores/ui';
  46. import { useSetupGlobalSocket, useSetupGlobalSocketForPage } from '~/stores/websocket';
  47. import loggerFactory from '~/utils/logger';
  48. import { BasicLayout } from '../components/Layout/BasicLayout';
  49. import GrowiContextualSubNavigationSubstance from '../components/Navbar/GrowiContextualSubNavigation';
  50. import type { GrowiSubNavigationSwitcherProps } from '../components/Navbar/GrowiSubNavigationSwitcher';
  51. import { DisplaySwitcher } from '../components/Page/DisplaySwitcher';
  52. import type { NextPageWithLayout } from './_app.page';
  53. import type { CommonProps } from './utils/commons';
  54. import {
  55. getNextI18NextConfig, getServerSideCommonProps, generateCustomTitleForPage, useInitSidebarConfig, skipSSR,
  56. } from './utils/commons';
  57. declare global {
  58. // eslint-disable-next-line vars-on-top, no-var
  59. var globalEmitter: EventEmitter;
  60. }
  61. const GrowiPluginsActivator = dynamic(() => import('~/features/growi-plugin/client/components').then(mod => mod.GrowiPluginsActivator), { ssr: false });
  62. const DescendantsPageListModal = dynamic(() => import('../components/DescendantsPageListModal').then(mod => mod.DescendantsPageListModal), { ssr: false });
  63. const UnsavedAlertDialog = dynamic(() => import('../components/UnsavedAlertDialog'), { ssr: false });
  64. const GrowiSubNavigationSwitcher = dynamic<GrowiSubNavigationSwitcherProps>(() => import('../components/Navbar/GrowiSubNavigationSwitcher')
  65. .then(mod => mod.GrowiSubNavigationSwitcher), { ssr: false });
  66. const DrawioModal = dynamic(() => import('../components/PageEditor/DrawioModal').then(mod => mod.DrawioModal), { ssr: false });
  67. const HandsontableModal = dynamic(() => import('../components/PageEditor/HandsontableModal').then(mod => mod.HandsontableModal), { ssr: false });
  68. const TemplateModal = dynamic(() => import('../components/TemplateModal').then(mod => mod.TemplateModal), { ssr: false });
  69. const LinkEditModal = dynamic(() => import('../components/PageEditor/LinkEditModal').then(mod => mod.LinkEditModal), { ssr: false });
  70. const PageStatusAlert = dynamic(() => import('../components/PageStatusAlert').then(mod => mod.PageStatusAlert), { ssr: false });
  71. const QuestionnaireModalManager = dynamic(() => import('~/features/questionnaire/client/components/QuestionnaireModalManager'), { ssr: false });
  72. const logger = loggerFactory('growi:pages:all');
  73. const {
  74. isPermalink: _isPermalink, isTrashPage: _isTrashPage, isCreatablePage,
  75. } = pagePathUtils;
  76. const { removeHeadingSlash } = pathUtils;
  77. type IPageToShowRevisionWithMeta = IDataWithMeta<IPagePopulatedToShowRevision & PageDocument, IPageInfoForEntity>;
  78. type IPageToShowRevisionWithMetaSerialized = IDataWithMeta<string, string>;
  79. superjson.registerCustom<IPageToShowRevisionWithMeta, IPageToShowRevisionWithMetaSerialized>(
  80. {
  81. isApplicable: (v): v is IPageToShowRevisionWithMeta => {
  82. return v?.data != null
  83. && v?.data.toObject != null
  84. && v?.meta != null
  85. && isIPageInfoForEntity(v.meta);
  86. },
  87. serialize: (v) => {
  88. return {
  89. data: superjson.stringify(v.data.toObject()),
  90. meta: superjson.stringify(v.meta),
  91. };
  92. },
  93. deserialize: (v) => {
  94. return {
  95. data: superjson.parse(v.data),
  96. meta: v.meta != null ? superjson.parse(v.meta) : undefined,
  97. };
  98. },
  99. },
  100. 'IPageToShowRevisionWithMetaTransformer',
  101. );
  102. // GrowiContextualSubNavigation for NOT shared page
  103. type GrowiContextualSubNavigationProps = {
  104. isLinkSharingDisabled: boolean,
  105. }
  106. const GrowiContextualSubNavigation = (props: GrowiContextualSubNavigationProps): JSX.Element => {
  107. const { isLinkSharingDisabled } = props;
  108. const { data: currentPage } = useSWRxCurrentPage();
  109. return (
  110. <div data-testid="grw-contextual-sub-nav">
  111. <GrowiContextualSubNavigationSubstance currentPage={currentPage} isLinkSharingDisabled={isLinkSharingDisabled}/>
  112. </div>
  113. );
  114. };
  115. const PutbackPageModal = (): JSX.Element => {
  116. const PutbackPageModal = dynamic(() => import('../components/PutbackPageModal'), { ssr: false });
  117. return <PutbackPageModal />;
  118. };
  119. type Props = CommonProps & {
  120. pageWithMeta: IPageToShowRevisionWithMeta | null,
  121. // pageUser?: any,
  122. redirectFrom?: string;
  123. // shareLinkId?: string;
  124. isLatestRevision?: boolean,
  125. isIdenticalPathPage?: boolean,
  126. isForbidden: boolean,
  127. isNotFound: boolean,
  128. isNotCreatable: boolean,
  129. // isAbleToDeleteCompletely: boolean,
  130. templateTagData?: string[],
  131. templateBodyData?: string,
  132. isSearchServiceConfigured: boolean,
  133. isSearchServiceReachable: boolean,
  134. isSearchScopeChildrenAsDefault: boolean,
  135. isSlackConfigured: boolean,
  136. // isMailerSetup: boolean,
  137. isAclEnabled: boolean,
  138. // hasSlackConfig: boolean,
  139. drawioUri: string | null,
  140. hackmdUri: string,
  141. noCdn: string,
  142. // highlightJsStyle: string,
  143. isAllReplyShown: boolean,
  144. isContainerFluid: boolean,
  145. editorConfig: EditorConfig,
  146. isEnabledStaleNotification: boolean,
  147. isEnabledAttachTitleHeader: boolean,
  148. // isEnabledLinebreaks: boolean,
  149. // isEnabledLinebreaksInComments: boolean,
  150. adminPreferredIndentSize: number,
  151. isIndentSizeForced: boolean,
  152. disableLinkSharing: boolean,
  153. skipSSR: boolean,
  154. grantData?: IPageGrantData,
  155. rendererConfig: RendererConfig,
  156. };
  157. const Page: NextPageWithLayout<Props> = (props: Props) => {
  158. // register global EventEmitter
  159. if (isClient() && window.globalEmitter == null) {
  160. window.globalEmitter = new EventEmitter();
  161. }
  162. const router = useRouter();
  163. useCurrentUser(props.currentUser ?? null);
  164. // commons
  165. useEditorConfig(props.editorConfig);
  166. useCsrfToken(props.csrfToken);
  167. useGrowiCloudUri(props.growiCloudUri);
  168. // page
  169. useIsContainerFluid(props.isContainerFluid);
  170. // useOwnerOfCurrentPage(props.pageUser != null ? JSON.parse(props.pageUser) : null);
  171. useIsForbidden(props.isForbidden);
  172. useIsNotCreatable(props.isNotCreatable);
  173. useRedirectFrom(props.redirectFrom ?? null);
  174. useIsSharedUser(false); // this page cann't be routed for '/share'
  175. useIsIdenticalPath(props.isIdenticalPathPage ?? false);
  176. useIsEnabledStaleNotification(props.isEnabledStaleNotification);
  177. useIsSearchPage(false);
  178. useIsEnabledAttachTitleHeader(props.isEnabledAttachTitleHeader);
  179. useIsSearchServiceConfigured(props.isSearchServiceConfigured);
  180. useIsSearchServiceReachable(props.isSearchServiceReachable);
  181. useIsSearchScopeChildrenAsDefault(props.isSearchScopeChildrenAsDefault);
  182. useIsSlackConfigured(props.isSlackConfigured);
  183. // useIsMailerSetup(props.isMailerSetup);
  184. useIsAclEnabled(props.isAclEnabled);
  185. // useHasSlackConfig(props.hasSlackConfig);
  186. useHackmdUri(props.hackmdUri);
  187. // useNoCdn(props.noCdn);
  188. useDefaultIndentSize(props.adminPreferredIndentSize);
  189. useIsIndentSizeForced(props.isIndentSizeForced);
  190. useDisableLinkSharing(props.disableLinkSharing);
  191. useRendererConfig(props.rendererConfig);
  192. // useRendererSettings(props.rendererSettingsStr != null ? JSON.parse(props.rendererSettingsStr) : undefined);
  193. // useGrowiRendererConfig(props.growiRendererConfigStr != null ? JSON.parse(props.growiRendererConfigStr) : undefined);
  194. useIsAllReplyShown(props.isAllReplyShown);
  195. useIsUploadableFile(props.editorConfig.upload.isUploadableFile);
  196. useIsUploadableImage(props.editorConfig.upload.isUploadableImage);
  197. const { pageWithMeta } = props;
  198. const pageId = pageWithMeta?.data._id;
  199. const pagePath = pageWithMeta?.data.path ?? props.currentPathname;
  200. const revisionBody = pageWithMeta?.data.revision?.body;
  201. usePageIdOnHackmd(pageWithMeta?.data.pageIdOnHackmd);
  202. useHasDraftOnHackmd(pageWithMeta?.data.hasDraftOnHackmd ?? false);
  203. useCurrentPathname(props.currentPathname);
  204. const { mutate: mutateInitialPage } = useSWRxCurrentPage();
  205. const { trigger: mutateCurrentPage } = useSWRMUTxCurrentPage();
  206. const { mutate: mutateEditingMarkdown } = useEditingMarkdown();
  207. const { data: currentPageId, mutate: mutateCurrentPageId } = useCurrentPageId();
  208. // Store initial data
  209. useEffect(() => {
  210. if (!props.skipSSR) {
  211. mutateInitialPage(pageWithMeta?.data ?? null);
  212. }
  213. }, [mutateInitialPage, pageWithMeta, props.skipSSR]);
  214. // Store initial data (When revisionBody is not SSR)
  215. useEffect(() => {
  216. if (!props.skipSSR) {
  217. return;
  218. }
  219. if (currentPageId != null && !props.isNotFound) {
  220. const mutatePageData = async() => {
  221. const pageData = await mutateCurrentPage();
  222. mutateEditingMarkdown(pageData?.revision.body);
  223. };
  224. // If skipSSR is true, use the API to retrieve page data.
  225. // Because pageWIthMeta does not contain revision.body
  226. mutatePageData();
  227. }
  228. }, [currentPageId, mutateCurrentPage, mutateEditingMarkdown, props.isNotFound, props.skipSSR]);
  229. const { mutate: mutateIsNotFound } = useIsNotFound();
  230. const { mutate: mutateIsLatestRevision } = useIsLatestRevision();
  231. const { data: grantData } = useSWRxIsGrantNormalized(pageId);
  232. const { mutate: mutateSelectedGrant } = useSelectedGrant();
  233. const { mutate: mutateRemoteRevisionId } = useRemoteRevisionId();
  234. const { mutate: mutateRevisionIdHackmdSynced } = useRevisionIdHackmdSynced();
  235. const { mutate: mutateTemplateTagData } = useTemplateTagData();
  236. const { mutate: mutateTemplateBodyData } = useTemplateBodyData();
  237. useSetupGlobalSocket();
  238. useSetupGlobalSocketForPage(pageId);
  239. const growiLayoutFluidClass = useCurrentGrowiLayoutFluidClassName(pageWithMeta?.data);
  240. const shouldRenderPutbackPageModal = pageWithMeta != null
  241. ? _isTrashPage(pageWithMeta.data.path)
  242. : false;
  243. // sync grant data
  244. useEffect(() => {
  245. const grantDataToApply = props.grantData ? props.grantData : grantData?.grantData.currentPageGrant;
  246. mutateSelectedGrant(grantDataToApply);
  247. }, [grantData?.grantData.currentPageGrant, mutateSelectedGrant, props.grantData]);
  248. // sync pathname by Shallow Routing https://nextjs.org/docs/routing/shallow-routing
  249. useEffect(() => {
  250. const decodedURI = decodeURI(window.location.pathname);
  251. if (isClient() && decodedURI !== props.currentPathname) {
  252. const { search, hash } = window.location;
  253. router.replace(`${props.currentPathname}${search}${hash}`, undefined, { shallow: true });
  254. }
  255. }, [props.currentPathname, router]);
  256. // initialize mutateEditingMarkdown only once per page
  257. // need to include useCurrentPathname not useCurrentPagePath
  258. useEffect(() => {
  259. if (props.currentPathname != null) {
  260. mutateEditingMarkdown(revisionBody);
  261. }
  262. }, [mutateEditingMarkdown, revisionBody, props.currentPathname]);
  263. useEffect(() => {
  264. mutateRemoteRevisionId(pageWithMeta?.data.revision?._id);
  265. mutateRevisionIdHackmdSynced(pageWithMeta?.data.revisionHackmdSynced);
  266. }, [mutateRemoteRevisionId, mutateRevisionIdHackmdSynced, pageWithMeta?.data.revision?._id, pageWithMeta?.data.revisionHackmdSynced]);
  267. useEffect(() => {
  268. mutateCurrentPageId(pageId ?? null);
  269. }, [mutateCurrentPageId, pageId]);
  270. useEffect(() => {
  271. mutateIsNotFound(props.isNotFound);
  272. }, [mutateIsNotFound, props.isNotFound]);
  273. useEffect(() => {
  274. mutateIsLatestRevision(props.isLatestRevision);
  275. }, [mutateIsLatestRevision, props.isLatestRevision]);
  276. useEffect(() => {
  277. mutateTemplateTagData(props.templateTagData);
  278. }, [props.templateTagData, mutateTemplateTagData]);
  279. useEffect(() => {
  280. mutateTemplateBodyData(props.templateBodyData);
  281. }, [props.templateBodyData, mutateTemplateBodyData]);
  282. const title = generateCustomTitleForPage(props, pagePath);
  283. return (
  284. <>
  285. <Head>
  286. <title>{title}</title>
  287. </Head>
  288. <div className={`dynamic-layout-root ${growiLayoutFluidClass} h-100 d-flex flex-column justify-content-between`}>
  289. <header className="py-0 position-relative">
  290. <div id="grw-subnav-container">
  291. <GrowiContextualSubNavigation isLinkSharingDisabled={props.disableLinkSharing} />
  292. </div>
  293. </header>
  294. <div className="d-edit-none">
  295. <GrowiSubNavigationSwitcher isLinkSharingDisabled={props.disableLinkSharing} />
  296. </div>
  297. <div id="grw-subnav-sticky-trigger" className="sticky-top"></div>
  298. <div id="grw-fav-sticky-trigger" className="sticky-top"></div>
  299. <DisplaySwitcher
  300. pageView={
  301. <PageView
  302. pagePath={pagePath}
  303. initialPage={pageWithMeta?.data}
  304. rendererConfig={props.rendererConfig}
  305. />
  306. }
  307. />
  308. <PageStatusAlert />
  309. {shouldRenderPutbackPageModal && <PutbackPageModal />}
  310. </div>
  311. </>
  312. );
  313. };
  314. type LayoutProps = Props & {
  315. children?: ReactNode
  316. }
  317. const Layout = ({ children, ...props }: LayoutProps): JSX.Element => {
  318. const className = useEditorModeClassName();
  319. // init sidebar config with UserUISettings and sidebarConfig
  320. useInitSidebarConfig(props.sidebarConfig, props.userUISettings);
  321. return (
  322. <BasicLayout className={className}>
  323. {children}
  324. </BasicLayout>
  325. );
  326. };
  327. Page.getLayout = function getLayout(page: React.ReactElement<Props>) {
  328. return (
  329. <>
  330. <GrowiPluginsActivator />
  331. <DrawioViewerScript />
  332. <Layout {...page.props}>
  333. {page}
  334. </Layout>
  335. <UnsavedAlertDialog />
  336. <DescendantsPageListModal />
  337. <DrawioModal />
  338. <HandsontableModal />
  339. <QuestionnaireModalManager />
  340. <TemplateModal />
  341. <LinkEditModal />
  342. </>
  343. );
  344. };
  345. function getPageIdFromPathname(currentPathname: string): string | null {
  346. return _isPermalink(currentPathname) ? removeHeadingSlash(currentPathname) : null;
  347. }
  348. class MultiplePagesHitsError extends ExtensibleCustomError {
  349. pagePath: string;
  350. constructor(pagePath: string) {
  351. super(`MultiplePagesHitsError occured by '${pagePath}'`);
  352. this.pagePath = pagePath;
  353. }
  354. }
  355. // apply parent page grant fot creating page
  356. async function applyGrantToPage(props: Props, ancestor: any) {
  357. await ancestor.populate('grantedGroup');
  358. const grant = {
  359. grant: ancestor.grant,
  360. };
  361. const grantedGroup = ancestor.grantedGroup ? {
  362. grantedGroup: {
  363. id: ancestor.grantedGroup.id,
  364. name: ancestor.grantedGroup.name,
  365. },
  366. } : {};
  367. props.grantData = Object.assign(grant, grantedGroup);
  368. }
  369. async function injectPageData(context: GetServerSidePropsContext, props: Props): Promise<void> {
  370. const { model: mongooseModel } = await import('mongoose');
  371. const req: CrowiRequest = context.req as CrowiRequest;
  372. const { crowi } = req;
  373. const { revisionId } = req.query;
  374. const Page = crowi.model('Page') as PageModel;
  375. const PageRedirect = mongooseModel('PageRedirect') as PageRedirectModel;
  376. const { pageService } = crowi;
  377. let currentPathname = props.currentPathname;
  378. const pageId = getPageIdFromPathname(currentPathname);
  379. const isPermalink = _isPermalink(currentPathname);
  380. const { user } = req;
  381. if (!isPermalink) {
  382. // check redirects
  383. const chains = await PageRedirect.retrievePageRedirectEndpoints(currentPathname);
  384. if (chains != null) {
  385. // overwrite currentPathname
  386. currentPathname = chains.end.toPath;
  387. props.currentPathname = currentPathname;
  388. // set redirectFrom
  389. props.redirectFrom = chains.start.fromPath;
  390. }
  391. // check whether the specified page path hits to multiple pages
  392. const count = await Page.countByPathAndViewer(currentPathname, user, null, true);
  393. if (count > 1) {
  394. throw new MultiplePagesHitsError(currentPathname);
  395. }
  396. }
  397. const pageWithMeta: IPageToShowRevisionWithMeta | null = await pageService.findPageAndMetaDataByViewer(pageId, currentPathname, user, true); // includeEmpty = true, isSharedPage = false
  398. const page = pageWithMeta?.data as unknown as PageDocument;
  399. // add user to seen users
  400. if (page != null && user != null) {
  401. await page.seen(user);
  402. }
  403. // populate & check if the revision is latest
  404. if (page != null) {
  405. page.initLatestRevisionField(revisionId);
  406. props.isLatestRevision = page.isLatestRevision();
  407. props.skipSSR = await skipSSR(page);
  408. await page.populateDataToShowRevision(props.skipSSR); // shouldExcludeBody = skipSSR
  409. }
  410. if (page == null && user != null) {
  411. const templateData = await Page.findTemplate(props.currentPathname);
  412. if (templateData != null) {
  413. props.templateTagData = templateData.templateTags as string[];
  414. props.templateBodyData = templateData.templateBody as string;
  415. }
  416. // apply pagrent page grant
  417. const ancestor = await Page.findAncestorByPathAndViewer(currentPathname, user);
  418. if (ancestor != null) {
  419. await applyGrantToPage(props, ancestor);
  420. }
  421. }
  422. props.pageWithMeta = pageWithMeta;
  423. }
  424. async function injectRoutingInformation(context: GetServerSidePropsContext, props: Props): Promise<void> {
  425. const req: CrowiRequest = context.req as CrowiRequest;
  426. const { crowi } = req;
  427. const Page = crowi.model('Page') as PageModel;
  428. const { currentPathname } = props;
  429. const pageId = getPageIdFromPathname(currentPathname);
  430. const isPermalink = _isPermalink(currentPathname);
  431. const page = props.pageWithMeta?.data;
  432. if (props.isIdenticalPathPage) {
  433. props.isNotCreatable = true;
  434. }
  435. else if (page == null) {
  436. props.isNotFound = true;
  437. props.isNotCreatable = !isCreatablePage(currentPathname);
  438. // check the page is forbidden or just does not exist.
  439. const count = isPermalink ? await Page.count({ _id: pageId }) : await Page.count({ path: currentPathname });
  440. props.isForbidden = count > 0;
  441. }
  442. else {
  443. props.isNotFound = page.isEmpty;
  444. props.isNotCreatable = false;
  445. props.isForbidden = false;
  446. // /62a88db47fed8b2d94f30000 ==> /path/to/page
  447. if (isPermalink && page.isEmpty) {
  448. props.currentPathname = page.path;
  449. }
  450. // /path/to/page ==> /62a88db47fed8b2d94f30000
  451. if (!isPermalink && !page.isEmpty) {
  452. const isToppage = pagePathUtils.isTopPage(props.currentPathname);
  453. if (!isToppage) {
  454. props.currentPathname = `/${page._id}`;
  455. }
  456. }
  457. }
  458. }
  459. // async function injectPageUserInformation(context: GetServerSidePropsContext, props: Props): Promise<void> {
  460. // const req: CrowiRequest = context.req as CrowiRequest;
  461. // const { crowi } = req;
  462. // const UserModel = crowi.model('User');
  463. // if (isUserPage(props.currentPagePath)) {
  464. // const user = await UserModel.findUserByUsername(UserModel.getUsernameByPath(props.currentPagePath));
  465. // if (user != null) {
  466. // props.pageUser = JSON.stringify(user.toObject());
  467. // }
  468. // }
  469. // }
  470. function injectServerConfigurations(context: GetServerSidePropsContext, props: Props): void {
  471. const req: CrowiRequest = context.req as CrowiRequest;
  472. const { crowi } = req;
  473. const {
  474. searchService, configManager, aclService,
  475. } = crowi;
  476. props.isSearchServiceConfigured = searchService.isConfigured;
  477. props.isSearchServiceReachable = searchService.isReachable;
  478. props.isSearchScopeChildrenAsDefault = configManager.getConfig('crowi', 'customize:isSearchScopeChildrenAsDefault');
  479. props.isSlackConfigured = crowi.slackIntegrationService.isSlackConfigured;
  480. // props.isMailerSetup = mailService.isMailerSetup;
  481. props.isAclEnabled = aclService.isAclEnabled();
  482. // props.hasSlackConfig = slackNotificationService.hasSlackConfig();
  483. props.drawioUri = configManager.getConfig('crowi', 'app:drawioUri');
  484. props.hackmdUri = configManager.getConfig('crowi', 'app:hackmdUri');
  485. props.noCdn = configManager.getConfig('crowi', 'app:noCdn');
  486. // props.highlightJsStyle = configManager.getConfig('crowi', 'customize:highlightJsStyle');
  487. props.isAllReplyShown = configManager.getConfig('crowi', 'customize:isAllReplyShown');
  488. props.isContainerFluid = configManager.getConfig('crowi', 'customize:isContainerFluid');
  489. props.isEnabledStaleNotification = configManager.getConfig('crowi', 'customize:isEnabledStaleNotification');
  490. props.disableLinkSharing = configManager.getConfig('crowi', 'security:disableLinkSharing');
  491. props.editorConfig = {
  492. upload: {
  493. isUploadableFile: crowi.fileUploadService.getFileUploadEnabled(),
  494. isUploadableImage: crowi.fileUploadService.getIsUploadable(),
  495. },
  496. };
  497. props.adminPreferredIndentSize = configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize');
  498. props.isIndentSizeForced = configManager.getConfig('markdown', 'markdown:isIndentSizeForced');
  499. props.isEnabledAttachTitleHeader = configManager.getConfig('crowi', 'customize:isEnabledAttachTitleHeader');
  500. props.rendererConfig = {
  501. isEnabledLinebreaks: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaks'),
  502. isEnabledLinebreaksInComments: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaksInComments'),
  503. adminPreferredIndentSize: configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize'),
  504. isIndentSizeForced: configManager.getConfig('markdown', 'markdown:isIndentSizeForced'),
  505. drawioUri: configManager.getConfig('crowi', 'app:drawioUri'),
  506. plantumlUri: configManager.getConfig('crowi', 'app:plantumlUri'),
  507. // XSS Options
  508. isEnabledXssPrevention: configManager.getConfig('markdown', 'markdown:rehypeSanitize:isEnabledPrevention'),
  509. xssOption: configManager.getConfig('markdown', 'markdown:rehypeSanitize:option'),
  510. attrWhitelist: JSON.parse(crowi.configManager.getConfig('markdown', 'markdown:rehypeSanitize:attributes')),
  511. tagWhitelist: crowi.configManager.getConfig('markdown', 'markdown:rehypeSanitize:tagNames'),
  512. highlightJsStyleBorder: crowi.configManager.getConfig('crowi', 'customize:highlightJsStyleBorder'),
  513. };
  514. }
  515. /**
  516. * for Server Side Translations
  517. * @param context
  518. * @param props
  519. * @param namespacesRequired
  520. */
  521. async function injectNextI18NextConfigurations(context: GetServerSidePropsContext, props: Props, namespacesRequired?: string[] | undefined): Promise<void> {
  522. const nextI18NextConfig = await getNextI18NextConfig(serverSideTranslations, context, namespacesRequired);
  523. props._nextI18Next = nextI18NextConfig._nextI18Next;
  524. }
  525. export const getServerSideProps: GetServerSideProps = async(context: GetServerSidePropsContext) => {
  526. const req = context.req as CrowiRequest<IUserHasId & any>;
  527. const { user } = req;
  528. const result = await getServerSideCommonProps(context);
  529. // check for presence
  530. // see: https://github.com/vercel/next.js/issues/19271#issuecomment-730006862
  531. if (!('props' in result)) {
  532. throw new Error('invalid getSSP result');
  533. }
  534. const props: Props = result.props as Props;
  535. if (props.redirectDestination != null) {
  536. return {
  537. redirect: {
  538. permanent: false,
  539. destination: props.redirectDestination,
  540. },
  541. };
  542. }
  543. if (user != null) {
  544. props.currentUser = user.toObject();
  545. }
  546. try {
  547. await injectPageData(context, props);
  548. }
  549. catch (err) {
  550. if (err instanceof MultiplePagesHitsError) {
  551. props.isIdenticalPathPage = true;
  552. }
  553. else {
  554. throw err;
  555. }
  556. }
  557. await injectRoutingInformation(context, props);
  558. injectServerConfigurations(context, props);
  559. await injectNextI18NextConfigurations(context, props, ['translation']);
  560. return {
  561. props,
  562. };
  563. };
  564. export default Page;